package com.googlecode.ozonbooksfinder.cairngormfinder.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.googlecode.ozonbooksfinder.cairngormfinder.business.BookFinderDelegate;
	import com.googlecode.ozonbooksfinder.cairngormfinder.event.GetBooksEvent;
	import com.googlecode.ozonbooksfinder.cairngormfinder.event.ShowViewEvent;
	import com.googlecode.ozonbooksfinder.cairngormfinder.model.CairngormFinderModelLocator;
	import com.googlecode.ozonbooksfinder.cairngormfinder.utils.BuildStronglyTypedBookVO;
	import com.googlecode.ozonbooksfinder.domain.Book;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.IResponder;
	
	public class GetBooksCommand extends SequenceCommand implements ICommand, IResponder
	{
		private var model:CairngormFinderModelLocator = CairngormFinderModelLocator.getInstance();
		
		private var searchString:String;
		
		private var searchContext:String;
		
		override public function execute(event:CairngormEvent):void
	   	{
	   		var delegate:BookFinderDelegate = new BookFinderDelegate(this);
	   		var evt:GetBooksEvent = GetBooksEvent(event);
	   		
	   		nextEvent = new ShowViewEvent(CairngormFinderModelLocator.VIEW_MAIN_BOOK_LIST);
	   		
	   		searchString = evt.searchString;
	   		searchContext = evt.searchContext;
	   		
	   		delegate.findItems(evt.searchString, evt.searchContext);
	   	}
	   	public function result(event:Object):void
		{
			var books:ArrayCollection = buildStronglyTypedVOCollection(event.result.Tables.SearchItems);
			
			model.currentSearchString = searchString;
			model.currentSearchContext = searchContext;
			
			model.booksDataProvider = books;
			
			executeNextCommand();
		}
	   	public function fault(event:Object):void
		{
			trace( "GetBooks Error:\n" + event.fault.faultDetail );
		}
		
		private function buildStronglyTypedVOCollection(items:Object):ArrayCollection
		{
			var books:ArrayCollection = new ArrayCollection();
			var columns:ArrayCollection = items.Columns;
			var rows:ArrayCollection = items.Rows;
			var book:Book;
			
			for (var i:int = 0; i < rows.length; ++i)
			{
				book = BuildStronglyTypedBookVO.build(rows[i]);
				books.addItemAt(book, i);
			}
			return books;
		}
	}
}